<?php
namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use common\models\Organization;

/**
 * Backend controller
 */
class BackendController extends Controller
{

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@']
                    ]
                ]
            ],
        ];
    }

    public function init(){
        $this->checkLogin();
        $this->checkAuthorization();
        $this->checkInitialization();

    }

    public function checkLogin(){
        if (Yii::$app->user->isGuest || !\Yii::$app->user->identity->organization_id ) {
            return $this->redirect('site/login');
        }
    }

    public function checkAuthorization(){
        $url = explode('?',Yii::$app->request->url);
        $route = trim($url[0]);
        $skipRoute = ["/","/site/index"];

        if(!in_array($route,$skipRoute)){
            if(!Yii::$app->user->can($route)) throw new ForbiddenHttpException(Yii::t('app', 'No Auth'));
        }
    }

	public function checkInitialization(){
        $initialization = Organization::getInfo()->initialization;
        if($initialization==0){
            return $this->redirect('/sys/initialization/index');
        }
	}



	

}
